package com.scpii.universal.pns.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.json.JSONException;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.doone.comm.paginaction.Pagination;
import com.scpii.universal.action.BaseAction;
import com.scpii.universal.constant.GenericConstants;
import com.scpii.universal.pns.dto.ClientUserDto;
import com.scpii.universal.pns.dto.FieldImageDto;
import com.scpii.universal.pns.dto.UserConfigDto;
import com.scpii.universal.pns.dto.UserDetailDto;
import com.scpii.universal.pns.entity.Field;
import com.scpii.universal.pns.entity.UserActionPointConfig;
import com.scpii.universal.pns.entity.UserLinks;
import com.scpii.universal.pns.entity.UserPointRanks;
import com.scpii.universal.pns.entity.Users;
import com.scpii.universal.pns.service.ClientUserManageService;
import com.scpii.universal.pns.service.DevicesService;
import com.scpii.universal.util.EhCacheManager;
import com.scpii.universal.util.FileUploadUtil;
import com.scpii.universal.util.ImgAndFilePath;
import com.scpii.universal.util.StreamUtil;

@Controller
@Scope("prototype")
public class UserManageAction extends BaseAction {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 4858773510657698933L;

	@Resource
	private ClientUserManageService clientUserManageService;

	@Resource
	private DevicesService devicesService;

	private Pagination page = new Pagination();
	private Pagination pageLevel = new Pagination();
	private Pagination pageDetail = new Pagination();
	private Pagination pagePoint = new Pagination();

	private List<Map<String, Object>> users;

	private String[] deviceModels;

	private ClientUserDto condition;
	private ClientUserDto clientUserDto;
	private List<UserDetailDto> udetailList;
	private List<UserPointRanks> userPointList;
	private List<UserActionPointConfig> pointConfigs;
	private String userId;

	private UserPointRanks userPointRanks;
	private String levelId;
	private String fieldId;
	private String editFlag;

	private UserConfigDto userConfigDto;
	private Map<Integer, String> regAllow;
	private Map<String, String> regType;
	private Map<String, String> fieldType;
	private List<FieldImageDto> fieldImageList;

	private List<Field> fieldList;

	private File fileMaterial;// Ajax获取图片文件,与控件type=File中的name属性一样
	private String fileMaterialFileName;// Ajax获取图片文件名称,相应的name属性名称+FileName

	private String t_weibo;
	private String s_weibo;

	private Map<String, String> actionTypeNames;
	private Map<Long, String> actionTypeTargetNames;
	private Map<String, String> timeKeyNames;

	private UserActionPointConfig pointConfig;

	private String messages;

	public String getClientUserInit() throws JSONException {

		if (condition == null) {
			condition = new ClientUserDto();
			condition.setUserType("NORMAL");
		}
		if (getSelectPerPage("page") == -1) {
			page.setPageRecord(10);
		} else {
			page.setPageRecord(getSelectPerPage("page"));
		}
		if (getQueryFlag("page") == -1) {
			page.setTotalRecord(clientUserManageService.getClientUserInitCount(
					getUserInfo().getAppId(), condition));
		} else {
			page.setTotalRecord(getQueryFlag("page"));
		}
		setPageParameters(page, "page");

		deviceModels = devicesService.getDevicesModelsByAppId(getUserInfo()
				.getAppId());
		users = clientUserManageService.getClientUserInit(getUserInfo()
				.getAppId(), condition, page.getCurrentPage(), page
				.getPageRecord());
		return SUCCESS;
	}

	public String getClientNewUserDetail() {

		clientUserDto = clientUserManageService.getUserDetailInfo(Long
				.parseLong(userId));

		if (clientUserDto != null) {
			clientUserManageService.getUserLinks(clientUserDto);
			// 获取社交账号
			List<UserLinks> list = clientUserDto.getUlks();
			if (list != null && list.size() > 0) {
				for (UserLinks links : list) {
					if (("T_SINA").equals(links.getProvider())) {
						s_weibo = links.getUserAlias();
					} else if ("T_TENCENT".equals(links.getProvider())) {
						t_weibo = links.getUserAlias();
					}
				}
			}
		}

		if (getSelectPerPage("pageDetail") == -1) {
			pageDetail.setPageRecord(10);
		} else {
			pageDetail.setPageRecord(getSelectPerPage("pageDetail"));
		}
		// 判断是否是第一次查询
		if (getQueryFlag("pageDetail") == -1) {
			pageDetail.setTotalRecord(clientUserManageService
					.getUserActionsByUserIdCount(Long.parseLong(userId)));
		} else {
			pageDetail.setTotalRecord(getQueryFlag("pageDetail"));
		}
		setPageParameters(pageDetail, "pageDetail");
		udetailList = clientUserManageService.getUserActionsByUserId(
				Long.parseLong(userId), pageDetail.getCurrentPage(),
				pageDetail.getPageRecord());

		// 用户配置字段
		fieldList = clientUserManageService.getUserFields(getUserInfo()
				.getAppId(), Long.parseLong(userId));

		return SUCCESS;
	}

	// --------------------用户积分等级配置开始----------------------------------------------------
	public String getUserLevelInit() {
		editFlag = "add";
		if (getSelectPerPage("pageLevel") == -1) {
			pageLevel.setPageRecord(GenericConstants.PAGE_NO);
		} else {
			pageLevel.setPageRecord(getSelectPerPage("pageLevel"));
		}
		// 判断是否是第一次查询
		if (getQueryFlag("pageLevel") == -1) {
			pageLevel.setTotalRecord(clientUserManageService
					.getUserLevelInitCount(getUserInfo().getAppId()));
		} else {
			pageLevel.setTotalRecord(getQueryFlag("pageLevel"));
		}
		setPageParameters(pageLevel, "pageLevel");
		userPointList = clientUserManageService.getUserLevelInit(getUserInfo()
				.getAppId(), pageLevel.getCurrentPage(), pageLevel
				.getPageRecord());
		return SUCCESS;
	}

	public String addUserLevel() {
		if (fileMaterial != null) {
			String absolutePath = getWebAppsRealPath() + getImgBasePath()
					+ ImgAndFilePath.USER;
			File file = new File(absolutePath);
			if (!file.exists()) {
				file.mkdirs();
			}
			String filePath = absolutePath + File.separator
					+ FileUploadUtil.generateIconName() + ".png";

			StreamUtil.uploadActiveImgs(fileMaterial, filePath);
			userPointRanks.setRankImg("/"
					+ filePath.replace(getWebAppsRealPath(), "").replace("\\",
							"/"));
		}
		userPointRanks.setAppid(GenericConstants.APP_ID_PRE
				+ getUserInfo().getAppId());
		userPointRanks.setDiscount((short) 1);
		userPointRanks.setCreateBy(Long.parseLong(getUserInfo().getIntUserId()
				.toString()));
		userPointRanks.setCreateDt(new Date());

		clientUserManageService.saveUserLevel(userPointRanks);
		return SUCCESS;
	}

	public String getUserlevelById() throws IOException {
		editFlag = "edit";
		UserPointRanks userPointRanks = clientUserManageService
				.getUserLevel(Long.parseLong(levelId));
		// 设置编码格式
		response.setCharacterEncoding("utf-8");
		// 将数据转换成前台js array格式的数据
		JSONObject data = new JSONObject();
		data.put("userPointRanks", userPointRanks);

		response.getWriter().print(data.toString());
		return null;
	}

	public String updateUserLevel() {
		if (fileMaterial != null) {
			String absolutePath = getWebAppsRealPath() + getImgBasePath()
					+ ImgAndFilePath.USER;
			File file = new File(absolutePath);
			if (!file.exists()) {
				file.mkdirs();
			}
			String filePath = absolutePath + File.separator
					+ FileUploadUtil.generateIconName() + ".png";

			StreamUtil.uploadActiveImgs(fileMaterial, filePath);
			userPointRanks.setRankImg("/"
					+ filePath.replace(getWebAppsRealPath(), "").replace("\\",
							"/"));
		}
		userPointRanks.setUpdateBy(Long.parseLong(getUserInfo().getIntUserId()
				.toString()));
		clientUserManageService.updateUserLevel(userPointRanks);
		return SUCCESS;
	}

	public String deleteUserLevel() {
		clientUserManageService.removeUserLevel(Long.parseLong(levelId));
		return null;
	}

	/**
	 * 用户配置
	 * 
	 * @return
	 */
	public String getUserConfigInit() {
		regAllow = new HashMap<Integer, String>();
		regType = new HashMap<String, String>();
		regAllow.put(1, "允许");
		regAllow.put(0, "不允许");
		regType.put("PHONE", "手机号码");
		regType.put("T_SINA", "新浪");
		regType.put("T_TENCENT", "腾讯");

		fieldType = new LinkedHashMap<String, String>();
		fieldType.put("TEXT", "文本");
		fieldType.put("RADIO", "单选");
		fieldType.put("CHECKBOX", "多选");
		fieldType.put("IMAGERADIO", "图文");
		fieldType.put("NUMBER", "数字");
		fieldType.put("DATE", "日期");
		fieldType.put("ADDRESS", "地址");
		fieldType.put("TEXTAREA", "文本域");
		fieldType.put("EMAIL", "邮箱");

		String serverUrl = EhCacheManager.getObject(
				GenericConstants.SERVER_URL_PREFIX).toString();

		userConfigDto = clientUserManageService.saveUserConfigInit(
				getUserInfo().getAppId(), getUserInfo().getIntUserId());
		if (userConfigDto != null && userConfigDto.getFieldList() != null) {

			FieldImageDto imageDto = null;
			for (Field field : userConfigDto.getFieldList()) {
				if (field.getUserRegFieldDto() != null) {
					String imgUrls = field.getUserRegFieldDto()
							.getOptionImageUrls().replace("[", "")
							.replace("]", "").replace("\"", "");
					if (imgUrls != null && !"".equals(imgUrls)) {
						fieldImageList = new ArrayList<FieldImageDto>();
						for (String str : imgUrls.split(",")) {
							imageDto = new FieldImageDto();
							if (str != null && str.startsWith("http://")) {
								imageDto.setFilePath(str);
							} else {
								imageDto.setFilePath(serverUrl + str);
							}
							fieldImageList.add(imageDto);
						}
						field.setFieldImageList(fieldImageList);
					} else {
						field.setFieldImageList(null);
					}
				}
				field.setTypeName(fieldType.get(field.getMetaType()));

			}
			userConfigDto.getFieldList();
		}
		return SUCCESS;
	}

	public String addUserConfig() {
		if (fieldImageList != null) {
			for (FieldImageDto imageDto : fieldImageList) {
				if (imageDto != null) {
					if (imageDto.getImageFile() != null) {
						String absolutePath = getWebAppsRealPath()
								+ getImgBasePath() + ImgAndFilePath.USER;
						File file = new File(absolutePath);
						if (!file.exists()) {
							file.mkdirs();
						}
						String filePath = absolutePath + File.separator
								+ FileUploadUtil.generateIconName() + ".png";
						StreamUtil.uploadActiveImgs(imageDto.getImageFile(),
								filePath);
						imageDto.setFilePath("/"
								+ filePath.replace(getWebAppsRealPath(), "")
										.replace("\\", "/"));
					}
				}
			}
		}

		clientUserManageService.saveUserConfig(userConfigDto, getUserInfo()
				.getAppId(), getUserInfo().getIntUserId(), fieldImageList);
		return SUCCESS;
	}

	public void updateUserConfigPre() throws IOException {
		try {
			clientUserManageService.updateUserConfigPre(userConfigDto,
					getUserInfo().getAppId());
			messages = "修改成功";
		} catch (Exception e) {
			messages = "修改失败请稍后再试";
		}
		HttpServletResponse response = getResponse();
		PrintWriter out = response.getWriter();
		out.print(messages);
		out.flush();
		out.close();
	}

	public String deleteUserField() {
		clientUserManageService.removeUserField(Long.parseLong(fieldId));
		return null;
	}

	// --------------------用户积分等级配置开结束----------------------------------------------------

	// ---------------------积分规则配置开始---------------------------------------------------------

	public String getPointConfigInit() {
		actionTypeNames = new LinkedHashMap<String, String>();
		actionTypeNames.put("USER_REGISTER", "注册");
		actionTypeNames.put("USER_LOGIN", "登录");
		actionTypeNames.put("ACTIVITIES_JOIN", "参加");
		actionTypeNames.put("ACTIVITIES_FAV", "收藏");
		actionTypeNames.put("ACTIVITIES_SHARE", "分享");
		actionTypeNames.put("EC_FAVORITE", "电商收藏");
		actionTypeNames.put("COMMENTS_ADD", "评论");
		actionTypeNames.put("REPLY_ADD", "回复");
		actionTypeNames.put("TARGET_VIEW", "页面查看");
		actionTypeNames.put("FIELD_FILL_IN", "填入必填");

		actionTypeTargetNames = new LinkedHashMap<Long, String>();
		actionTypeTargetNames.put(48l, "内容");
		actionTypeTargetNames.put(40l, "圈子");
		actionTypeTargetNames.put(37l, "电商");

		timeKeyNames = new LinkedHashMap<String, String>();
		timeKeyNames.put("m", "分");
		timeKeyNames.put("h", "时");
		timeKeyNames.put("d", "天");
		timeKeyNames.put("M", "月");
		timeKeyNames.put("y", "年");

		if (getSelectPerPage("pagePoint") == -1) {
			pagePoint.setPageRecord(GenericConstants.PAGE_NO);
		} else {
			pagePoint.setPageRecord(getSelectPerPage("pagePoint"));
		}
		// 判断是否是第一次查询
		if (getQueryFlag("pagePoint") == -1) {
			pagePoint.setTotalRecord(clientUserManageService
					.getPointConfigInitCount(getUserInfo().getAppId()));
		} else {
			pagePoint.setTotalRecord(getQueryFlag("pagePoint"));
		}
		setPageParameters(pagePoint, "pagePoint");
		pointConfigs = clientUserManageService.getPointConfigInit(getUserInfo()
				.getAppId(), pagePoint.getCurrentPage(), pagePoint
				.getPageRecord());
		return SUCCESS;
	}

	public void addPointConfig() throws IOException {
		boolean isAdded = clientUserManageService
				.getPointConfigByTypeAndTarget(pointConfig.getActionType(),
						pointConfig.getTargetId(), getUserInfo().getAppId());
		HttpServletResponse response = getResponse();
		response.setContentType("text/plain");
		PrintWriter out = response.getWriter();
		if (isAdded) {
			out.print("error");
			out.flush();
			out.close();
			return;
		}
		clientUserManageService.saveUsePoint(pointConfig, getUserInfo()
				.getAppId(), getUserInfo().getIntUserId());
		out.print("success");
		out.flush();
		out.close();
	}

	public void deletePointConfig() throws IOException {
		HttpServletResponse response = getResponse();
		response.setContentType("text/plain");
		PrintWriter out = response.getWriter();
		clientUserManageService.removePointConfigById(pointConfig.getId());
		out.print("success");
		out.flush();
		out.close();
	}

	public String editPointConfig() throws IOException {
		pointConfig = clientUserManageService.getPointConfig(pointConfig
				.getId());
		return SUCCESS;
	}

	public void doEditPointConfig() throws IOException {
		clientUserManageService.updatePointConfig(pointConfig, getUserInfo()
				.getIntUserId());
		HttpServletResponse response = getResponse();
		response.setContentType("text/plain");
		PrintWriter out = response.getWriter();

		out.print("success");
		out.flush();
		out.close();
	}

	// ---------------------积分规则配置结束---------------------------------------------------------

	// -------------------------用户添加开始---------------
	public void checkUserName() throws IOException {
		HttpServletResponse response = getResponse();
		response.setContentType("text/json");
		PrintWriter out = response.getWriter();
		if (clientUserDto != null
				&& !StringUtils.isBlank(clientUserDto.getUserName())) {
			Boolean isExists = clientUserManageService.checkUserName(
					clientUserDto.getUserName(), getUserInfo().getAppId());
			out.print(!isExists);
		} else {
			out.print(false);
		}
		out.flush();
		out.close();
	}

	public void addUsers() throws IOException {
		HttpServletResponse response = getResponse();
		response.setContentType("text/json");
		PrintWriter out = response.getWriter();
		Users users = new Users();
		users.setUserName(clientUserDto.getUserName());
		users.setPassword(DigestUtils.md5Hex(clientUserDto.getPassword()));
		users.setUserAilas(clientUserDto.getUserAilas());
		users.setAuthorities("ROLE_CLIENT,ROLE_USER");
		users.setCreateDt(new Date());
		users.setUserType("NOT_VERIF");
		users.setCreateBy(getUserInfo().getIntUserId());
		users.setAppId(GenericConstants.APP_ID_PRE + getUserInfo().getAppId());
		users.setPasswordFormat("MD5");
		users.setProvider("PHONE");
		if (fileMaterial != null) {
			String absolutePath = getWebAppsRealPath() + getImgBasePath()
					+ ImgAndFilePath.USER;
			File file = new File(absolutePath);
			if (!file.exists()) {
				file.mkdirs();
			}
			String filePath = absolutePath + File.separator
					+ FileUploadUtil.generateIconName() + ".png";

			StreamUtil.uploadActiveImgs(fileMaterial, filePath);
			users.setAvatar("/"
					+ filePath.replace(getWebAppsRealPath(), "").replace("\\",
							"/"));
		}
		try {
			clientUserManageService.saveUsers(users);
			out.print("success");
		} catch (Exception e) {
			out.print("error");
		}
		out.flush();
		out.close();
	}

	// ------------------------用户添加结束---------------

	public Pagination getPage() {
		return page;
	}

	public void setPage(Pagination page) {
		this.page = page;
	}

	public List<Map<String, Object>> getUsers() {
		return users;
	}

	public void setUsers(List<Map<String, Object>> users) {
		this.users = users;
	}

	public ClientUserDto getCondition() {
		return condition;
	}

	public void setCondition(ClientUserDto condition) {
		this.condition = condition;
	}

	public Pagination getPageDetail() {
		return pageDetail;
	}

	public void setPageDetail(Pagination pageDetail) {
		this.pageDetail = pageDetail;
	}

	public ClientUserDto getClientUserDto() {
		return clientUserDto;
	}

	public void setClientUserDto(ClientUserDto clientUserDto) {
		this.clientUserDto = clientUserDto;
	}

	public List<UserDetailDto> getUdetailList() {
		return udetailList;
	}

	public void setUdetailList(List<UserDetailDto> udetailList) {
		this.udetailList = udetailList;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		if (userId != null && !"".equals(userId)) {
			String[] names = userId.split(",");
			if (names != null && names.length > 0) {
				userId = names[0];
			}
		}
		this.userId = userId;
	}

	public Pagination getPageLevel() {
		return pageLevel;
	}

	public void setPageLevel(Pagination pageLevel) {
		this.pageLevel = pageLevel;
	}

	public List<UserPointRanks> getUserPointList() {
		return userPointList;
	}

	public void setUserPointList(List<UserPointRanks> userPointList) {
		this.userPointList = userPointList;
	}

	public String getT_weibo() {
		return t_weibo;
	}

	public void setT_weibo(String t_weibo) {
		this.t_weibo = t_weibo;
	}

	public String getS_weibo() {
		return s_weibo;
	}

	public void setS_weibo(String s_weibo) {
		this.s_weibo = s_weibo;
	}

	public UserPointRanks getUserPointRanks() {
		return userPointRanks;
	}

	public void setUserPointRanks(UserPointRanks userPointRanks) {
		this.userPointRanks = userPointRanks;
	}

	public File getFileMaterial() {
		return fileMaterial;
	}

	public void setFileMaterial(File fileMaterial) {
		this.fileMaterial = fileMaterial;
	}

	public String getFileMaterialFileName() {
		return fileMaterialFileName;
	}

	public void setFileMaterialFileName(String fileMaterialFileName) {
		this.fileMaterialFileName = fileMaterialFileName;
	}

	public String getLevelId() {
		return levelId;
	}

	public void setLevelId(String levelId) {
		this.levelId = levelId;
	}

	public String getEditFlag() {
		return editFlag;
	}

	public void setEditFlag(String editFlag) {
		this.editFlag = editFlag;
	}

	public UserConfigDto getUserConfigDto() {
		return userConfigDto;
	}

	public void setUserConfigDto(UserConfigDto userConfigDto) {
		this.userConfigDto = userConfigDto;
	}

	public Map<Integer, String> getRegAllow() {
		return regAllow;
	}

	public void setRegAllow(Map<Integer, String> regAllow) {
		this.regAllow = regAllow;
	}

	public Map<String, String> getRegType() {
		return regType;
	}

	public void setRegType(Map<String, String> regType) {
		this.regType = regType;
	}

	public String getFieldId() {
		return fieldId;
	}

	public void setFieldId(String fieldId) {
		this.fieldId = fieldId;
	}

	public List<FieldImageDto> getFieldImageList() {
		return fieldImageList;
	}

	public void setFieldImageList(List<FieldImageDto> fieldImageList) {
		this.fieldImageList = fieldImageList;
	}

	public List<Field> getFieldList() {
		return fieldList;
	}

	public void setFieldList(List<Field> fieldList) {
		this.fieldList = fieldList;
	}

	public List<UserActionPointConfig> getPointConfigs() {
		return pointConfigs;
	}

	public void setPointConfigs(List<UserActionPointConfig> pointConfigs) {
		this.pointConfigs = pointConfigs;
	}

	public Map<String, String> getActionTypeNames() {
		return actionTypeNames;
	}

	public void setActionTypeNames(Map<String, String> actionTypeNames) {
		this.actionTypeNames = actionTypeNames;
	}

	public Map<Long, String> getActionTypeTargetNames() {
		return actionTypeTargetNames;
	}

	public void setActionTypeTargetNames(Map<Long, String> actionTypeTargetNames) {
		this.actionTypeTargetNames = actionTypeTargetNames;
	}

	public Map<String, String> getTimeKeyNames() {
		return timeKeyNames;
	}

	public void setTimeKeyNames(Map<String, String> timeKeyNames) {
		this.timeKeyNames = timeKeyNames;
	}

	public Pagination getPagePoint() {
		return pagePoint;
	}

	public void setPagePoint(Pagination pagePoint) {
		this.pagePoint = pagePoint;
	}

	public UserActionPointConfig getPointConfig() {
		return pointConfig;
	}

	public void setPointConfig(UserActionPointConfig pointConfig) {
		this.pointConfig = pointConfig;
	}

	public Map<String, String> getFieldType() {
		return fieldType;
	}

	public void setFieldType(Map<String, String> fieldType) {
		this.fieldType = fieldType;
	}

	public String getMessages() {
		return messages;
	}

	public void setMessages(String messages) {
		this.messages = messages;
	}

	public String[] getDeviceModels() {
		return deviceModels;
	}

	public void setDeviceModels(String[] deviceModels) {
		this.deviceModels = deviceModels;
	}

}
